'''
Created on Sep 20, 2012

@author: daoxuandung
'''

from google.appengine.api import memcache
from kid import util
import logging
import webapp2
from datetime import datetime


def increase_vote(vote):
    # Add a taskqueue to update vote. Rate is 1s
    task_name = vote.article.urlsafe()
    util.add_cron(path=webapp2.uri_for('update-stat'), 
                  name=task_name, 
                  interval=1, 
                  when=datetime.now(), 
                  params=util.ndb_to_dict(vote))
    
def cache_view(article_key):
    client = memcache.Client()
    mem_key = article_key.urlsafe() + "views"
    views = client.get(mem_key)
    if not views:
        views = 0
    client.set(mem_key, views + 1)

    
def increase_view(article_key):
    # Cache views into memcache
    cache_view(article_key)
    
    # Update the views to datastore if possible. Rate is 1 mins
    task_name = article_key.urlsafe()
    params = {}
    params['article'] = article_key.id()
    util.add_cron(path=webapp2.uri_for('update-stat'), 
                  name=task_name, 
                  interval=60, 
                  when=datetime.now(), 
                  params=params)


def cache_comment(article_key):
    client = memcache.Client()
    mem_key = article_key.urlsafe() + "comments"
    comments = client.get(mem_key)
    if not comments:
        comments = 0
    client.set(mem_key, comments + 1)

    
def increase_comment(article_key):
    # Cache views into memcache
    cache_comment(article_key)
    
    # Update the views to datastore if possible. Rate is 1 mins
    task_name = article_key.urlsafe()
    params = {}
    params['article'] = article_key.id()
    util.add_cron(path=webapp2.uri_for('update-stat'), 
                  name=task_name, 
                  interval=1, 
                  when=datetime.now(), 
                  params=params)
    